﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace MoneyWentWhere.DataModel.Reports
{
    public static class TimeUtils
    {
        public static DateTime PeriodStart(this DateTime time, TimeSpanUnit unit)
        {
            switch (unit)
            {
                case TimeSpanUnit.Day: 
                    return time.Date;
                case TimeSpanUnit.Week: 
                    // See when the week starts
                    DayOfWeek start = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
                    DayOfWeek now = time.DayOfWeek;
                    int diff = start - now;
                    if (diff > 0) { diff -= 7; }
                    return time.Date.AddDays(diff);
                case TimeSpanUnit.Month:
                    return new DateTime(time.Year, time.Month, 1);
                case TimeSpanUnit.QuarterYear:
                    if (time.Month <= 3) { return new DateTime(time.Year, 1, 1); }
                    if (time.Month <= 6) { return new DateTime(time.Year, 4, 1); }
                    if (time.Month <= 9) { return new DateTime(time.Year, 7, 1); }
                    return new DateTime(time.Year, 10, 1); 
                case TimeSpanUnit.HalfYear:
                    if (time.Month <= 6) { return new DateTime(time.Year, 1, 1); }
                    return new DateTime(time.Year,7, 1);
                case TimeSpanUnit.Year:
                    return new DateTime(time.Year, 1, 1);
                default:
                    throw new NotImplementedException("No impl for: " + unit);
            }
        }
        public static TimeSpan PeriodDuration(this DateTime time, TimeSpanUnit unit)
        {
            DateTime start = time.PeriodStart(unit);
            switch (unit)
            {
                case TimeSpanUnit.Day:
                    return TimeSpan.FromDays(1);
                case TimeSpanUnit.Week:
                    return TimeSpan.FromDays(7);
                case TimeSpanUnit.Month:
                    return start.AddMonths(1) - start;
                case TimeSpanUnit.QuarterYear:
                    return start.AddMonths(3) - start;
                case TimeSpanUnit.HalfYear:
                    return start.AddMonths(6) - start;
                case TimeSpanUnit.Year:
                    return start.AddYears(1) - start;
                default:
                    throw new NotImplementedException("No impl for: " + unit); 
            }
        }
    }


}
